package com.itheima.cs.adapter.dbd;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.itheima.cs.R;
import com.itheima.cs.entity.dbd.WarehouseInfo;
import java.util.List;

public class StockAdapter extends RecyclerView.Adapter<StockAdapter.ViewHolder> {

    private final List<WarehouseInfo> dataList;
    private final OnItemClickListener listener;
    private int selectedPosition = -1;

    public interface OnItemClickListener {
        void onItemClick(WarehouseInfo stock);
    }

    public StockAdapter(List<WarehouseInfo> dataList, OnItemClickListener listener) {
        this.dataList = dataList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_stock, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        WarehouseInfo item = dataList.get(position);
        holder.tvNumber.setText("仓库编码：" + item.getNumber());
        holder.tvName.setText("仓库名称：" + item.getName());

        holder.radioButton.setChecked(position == selectedPosition);
        holder.radioButton.setOnClickListener(v -> {
            setSelectedPosition(position);
            listener.onItemClick(item);
        });

        holder.itemView.setOnClickListener(v -> {
            setSelectedPosition(position);
            listener.onItemClick(item);
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public void setSelectedPosition(int position) {
        if (position == RecyclerView.NO_POSITION) return;
        int previous = selectedPosition;
        selectedPosition = position;
        notifyItemChanged(previous);
        notifyItemChanged(selectedPosition);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        RadioButton radioButton;
        TextView tvNumber;
        TextView tvName;

        ViewHolder(View itemView) {
            super(itemView);
            radioButton = itemView.findViewById(R.id.radio_button);
            tvNumber = itemView.findViewById(R.id.tv_number);
            tvName = itemView.findViewById(R.id.tv_name);
        }
    }
}
